package com.kingsailor.gunsmith.admin.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kingsailor.gunsmith.FastAppConfigHolder;
import com.kingsailor.gunsmith.FastAppConstants;
import edu.jetwinner.util.FastRandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.util.FileCopyUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPOutputStream;

/**
 * @author xulixin
 */
public class ConfigResourceLoaderServlet extends HttpServlet {

    private static final Logger log = LoggerFactory.getLogger(ConfigResourceLoaderServlet.class);

    private static final String AJAX = "json";

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        byte[] outBytes = "".getBytes();
        String __ajax = req.getParameter("__ajax");
        String scheme = req.getScheme();
        String serverName = req.getServerName();
        int port = req.getServerPort();
        port = (port == 443 || port == 80) ? 0 : port;
        String path = req.getContextPath();
        String basePath = scheme + "://" + serverName + (port == 0 ? "" : (":" + port)) + path;
        String userName = "loginUserEntity";
        String name = "loginUserEntity";
        String userId = "loginUserEntity";
        if (__ajax != null) {
            // AJAX返回JSON
            if (AJAX.equals(__ajax)) {
                resp.setContentType("application/json; charset=utf-8");
                resp.setCharacterEncoding("UTF-8");

                ObjectMapper objectMapper = new ObjectMapper();

                // 构造一个包含数据的对象
                Map<String, String> data = new HashMap<>();
                data.put("baseURL", path + "/");
                data.put("ctx", path);
//                data.put("_lang", StrUtil.nullToDefault(CookieUtil.getCookie(req, ConfigConstant.LANGUAGE), LocaleContextHolder.getLocale().toString()));
                data.put("_username", userName);
                data.put("__NAME__", name);
                data.put("userId", userId);
                data.put("_secretkey", FastAppConstants.PUBKEY);
                data.put("_i18n_tag", FastAppConstants.I18N_TAG);
                data.put("__DICTTAG__", FastAppConstants.DICT_TAG);
                data.put("_VERSION", FastAppConstants.F_VSRION);
//                data.put("title", Global.getConfig("SYS_CONFIG_TITLE"));
//                data.put("sysConfig", JSONUtil.parseObj(Global.getConfig(ConfigConstant.SYS_CONFIG_KEY)));
                data.put("tenantModel",
                        FastAppConfigHolder.me().getProperty("tenantModelEnabled", "false"));
//                data.put("valideLogin", Global.isValidCode());
//                data.put("isValidationCode", Global.isValidationCode());

                // 将对象转换为JSON字符串
                String jsonData = objectMapper.writeValueAsString(data);
                try (PrintWriter out = resp.getWriter()) {
                    out.print(jsonData);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        } else {
            StringBuffer _default = _default(path, LocaleContextHolder.getLocale().toString(), userName, name, userId)
                    .append(String.format(",basePath='%s';", basePath));
            // 无头像设置默认
            _default.append("function imgUserError(){var img=event.srcElement;img.src=baseURL+\"static/img/user2-160x160.jpg\"; img.onerror=null;};");
            if (!FastAppConstants.LIC_TAG.equals("SUCCESS")) {
                _default.append(";$(function() {" +
                        "var lic = $('<div id=\"" + FastRandomUtil.randomString(5) + "\" style=\"position: fixed;right: 100px;overflow: hidden;z-index: 19920219;" +
                        "pointer-events: none;opacity: 0.2;font-size: 14px;font-family: Microsoft YaHei UI,Microsoft YaHei;color: rgb(255 0 0);" +
                        "text-align: center;display: block;bottom: 7px;font-weight: bold;\">软件未注册" +
                        "<span style=\"font-size: 12px;\">(Gunsmith)</span></div>');" +
                        "if(!(self.frameElement && self.frameElement.tagName == \"IFRAME\")){" +
                        "if($('.wrapper > footer').length == 0){" +
                        "lic.css('bottom','');" +
                        "lic.css('top','10px');" +
                        "lic.css('right','10px');" +
                        "}" +
                        "var __index = Math.floor((Math.random()* $('body').children().length));" +
                        "window.setTimeout(function(){$($('body').children()[__index]).after(lic);},200);" +
                        "}" +
                        "});");
            }
            outBytes = _default.toString().getBytes();
            if (log.isDebugEnabled()) {
                log.debug("压缩前:{}", outBytes.length);
            }
            // 用GZIPOutputStream压缩
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(bout);
            gzip.write(outBytes);
            // 一般输出都要flush
            gzip.flush();
            gzip.close();
            outBytes = bout.toByteArray();
            if (log.isDebugEnabled()) {
                log.debug("压缩之后:{}" + outBytes.length);
            }
            resp.setContentType("text/javascript");
            // 注明压缩类型
            resp.setHeader("content-encoding", "gzip");
            resp.setHeader("content-length", String.valueOf(outBytes.length));
            try (ServletOutputStream out = resp.getOutputStream()) {
                FileCopyUtils.copy(outBytes, out);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 默认返回信息
     *
     * @return
     */
    public StringBuffer _default(String baseURL, String lang, String _username, String name, String userId) {
        StringBuffer buf = new StringBuffer();
        buf.append("/*!\n" +
                " * @author Gunsmith\n" +
                " * @date 2024-02-12\n" +
                " */\n");
        buf.append(String.format("var baseURL='%s/',ctx='%s',__LANG__='%s',", baseURL, baseURL, lang));
        buf.append(String.format("__USERNAME__='%s',__NAME__='%s',__USERID__='%s',", _username, name, userId));
        buf.append(String.format("__SECRETKEY__='%s',", FastAppConstants.PUBKEY));
//        sb.append(String.format("__LOCKSCREEN__='%s',", Global.getDbKey("SYS_LOCK_SCEREEN")));
        buf.append(String.format("__I18NTAG__='%s',", FastAppConstants.I18N_TAG));
        buf.append(String.format("__DICTTAG__='%s',", FastAppConstants.DICT_TAG));
        buf.append(String.format("__VERSION__='%s',", FastAppConstants.F_VSRION));
        buf.append(String.format("__ISCSRF__=%s", FastAppConfigHolder.me().getProperty("csrfEnabled", "false")));
        return buf;
    }
}
